package cn.kbyue.ormdemo.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author xlang
 * @date 2023/4/12 9:56
 */
@Slf4j
@Component
public class MybatisPlusMetaHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (metaObject.hasSetter("createTime")) {
                this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            }
        } catch (Exception e) {
            log.error("[MybatisPlusMetaHandler] 自动填充失败: {} insert. e: {}", metaObject.getOriginalObject().getClass().getName(), e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (metaObject.hasSetter("updateTime")) {
                this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }
        } catch (Exception e) {
            log.error("[MybatisPlusMetaHandler] 自动填充失败: {} update. e: {}", metaObject.getOriginalObject().getClass().getName(), e.getMessage());
        }
    }

}
